package com.kin207.netty.message.http.handler;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import jdk.nashorn.api.scripting.JSObject;

import com.alibaba.fastjson.JSONObject;
import com.kin207.netty.message.http.util.MessageAssembleUtil;
import com.kin207.netty.server.IServer;
import com.kin207.netty.server.ServerManager;
import com.kin207.netty.session.SessionManager;

public class HttpMessageHttpHandle implements HttpHandler {
	final static Logger logger = LoggerFactory.getLogger(HttpMessageHttpHandle.class);
	
	private IServer server;
	
	public HttpMessageHttpHandle() {

	}

	public HttpMessageHttpHandle(IServer server) {
		this.server = server;
	}

	public void handle(HttpExchange httpExchange) throws IOException {
		int code = -1;
		try {
			Headers headers = httpExchange.getRequestHeaders();
			String cid = headers.getFirst("cid");
			String sid = headers.getFirst("sid");
			String msgType = headers.getFirst("messageType");
			String groupName = headers.getFirst("groupName");
			String clientName = headers.getFirst("clientId");
			String message = IOUtils.toString(httpExchange.getRequestBody(), "UTF-8");
			logger.debug("on handle, cid:{}, sid:{}, messageType:{}, clientName:{}, groupName:{}, message:{}", cid, sid, msgType, clientName, groupName, message);
			IServer cserver = sid==null?server:ServerManager.getShared().getServer(sid);
			SessionManager sm = cserver.getSessionManager();
			if(msgType==null || "openlock".contentEquals(msgType)) {
				JSONObject sendMessage= JSONObject.parseObject(message);
				String msg = MessageAssembleUtil.openAssemble( clientName, sendMessage.getString("cmdcode"));
				if(clientName!=null && !"".equals(clientName)) {
					code = sm.sendMessageForName(clientName, msg,System.currentTimeMillis());
				}else {
					code = sm.sendMessage(cid, msg,System.currentTimeMillis());
				}
			}
			else if ("s2c".equals(msgType)) {
				if(clientName!=null && !"".equals(clientName)) {
					code = sm.sendMessageForName(clientName, message,System.currentTimeMillis());
				}else {
					code = sm.sendMessage(cid, message,System.currentTimeMillis());
				}
			} else if ("s2g".equals(msgType)) {
				code = sm.sendGroupMessage(groupName, message,System.currentTimeMillis());
			} else if ("s2s".equals(msgType)) {
				code = sm.sendSystemMessage(message,System.currentTimeMillis());
			}
			if(code==0) {
				response(httpExchange, 200, String.valueOf(code), "success");
			}else {
				response(httpExchange, 300, String.valueOf(code), "failed"); 
			}
		} catch(Exception e){
			logger.error(e.getMessage() , e);
			response(httpExchange, 500, String.valueOf(code), e.getMessage());
		}
		
		
	}
	
	public void response(HttpExchange httpExchange , int httpCode, String code, String errInfo) throws IOException{
		final byte[] res = ("{\"code\":\""+code+"\", \"message\":\""+(errInfo)+"\"}").getBytes();
		Headers headers = httpExchange.getResponseHeaders();
		headers.add("Content-Type", "text/json; charset=utf-8");
		
		httpExchange.sendResponseHeaders(httpCode, res.length);
		httpExchange.getResponseBody().write(res);
		httpExchange.getResponseBody().flush();
		httpExchange.getResponseBody().close();
	}

	public IServer getServer() {
		return server;
	}

	public void setServer(IServer server) {
		this.server = server;
	}

}
